package com.programmeur.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DAOFactory {
	private static final String FICHIER_PROPERTIES = "/com/programmeur/dao/dao.properties";
	private static final String PROPERTIES_URL = "url";
	private static final String PROPERTIES_DRIVER = "driver";
	private static final String PROPERTIES_UTILISATEUR = "nom_utilisateur";
	private static final String PROPERTIES_MOTDEPASSE = "motdepasse";

	private String url;
	private String username;
	private String password;

	public DAOFactory(String url, String username, String password) {
		this.url = url;
		this.username = username;
		this.password = password;
	}

	public static DAOFactory getInstance() throws DAOConfigurationException {
		Properties properties = new Properties();
		String url;
		String driver;
		String nomUtilisateur;
		String motDePasse;
		ClassLoader classloader = Thread.currentThread()
				.getContextClassLoader();
		InputStream fichierProperties = classloader
				.getResourceAsStream(FICHIER_PROPERTIES);
		if (fichierProperties == null) {
			throw new DAOConfigurationException(" le fichier "
					+ FICHIER_PROPERTIES + " est introuvable");
		}
		try {
			properties.load(fichierProperties);
			url = properties.getProperty(PROPERTIES_URL);
			driver = properties.getProperty(PROPERTIES_DRIVER);
			nomUtilisateur = properties.getProperty(PROPERTIES_UTILISATEUR);
			motDePasse = properties.getProperty(PROPERTIES_MOTDEPASSE);

		} catch (IOException e) {
			throw new DAOConfigurationException(
					" impossible de charger le fichier properties "
							+ FICHIER_PROPERTIES);
		}
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			throw new DAOConfigurationException(
					" les driver est introuvable dans le classpath. ", e);
		}
		DAOFactory instance = new DAOFactory(url, nomUtilisateur, motDePasse);
		return instance;
	}

	Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, username, password);
	}

	public UtilisateurDao getUtilisateurDao() {
		return new UtilisateurDaoImpl(this);
	}
	public NewsDao getNewsDao(){
		return new NewsDaoImpl(this);
	}

}
